<template>
  <a-modal
    title="追加合同"
    :width="720"
    centered
    :visible="visible"
    :confirmLoading="loading"
    @ok="_submit"
    @cancel="_cancel"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <a-form-item v-show="false" label="主键ID">
          <a-input v-decorator="['contractNo', { initialValue: '' }]" disabled />
        </a-form-item>
        <a-form-item label="服务费">
          <a-input
            v-decorator="[
              'serviceFeeAmount',
              { rules: [{ required: true, message: '请填写服务费，服务费不能为空!' }] },
            ]"
          />
        </a-form-item>
        <a-form-item label="图片">
          <a-upload
            list-type="picture-card"
            :file-list="fileList"
            :customRequest="customRequest"
            :remove="delFile"
            @preview="handlePreview"
            v-decorator="['pics', { rules: [{ required: true, message: '图片不能为空!' }] }]"
          >
            <div v-if="fileList.length < 8">
              <a-icon type="plus" />
              <div class="ant-upload-text">Upload</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-form-item>
      </a-form>
      <a-descriptions>
        <template #title><a>合同选择</a></template>
        <a-descriptions-item>
          <a-table
            row-key="contractNo"
            :columns="columns"
            :data-source="model.contractList"
            :rowSelection="{ selectedRowKeys: this.selectedRowKeys, onChange: this.onSelectChange }"
            v-if="model?.contractList"
          >
            <span slot="serial" slot-scope="text, record, index">
              {{ index + 1 }}
            </span>
            <div slot="userInfo" slot-scope="text, record">
              <div>
                <span>{{ record.userName }}</span
                >&nbsp;&nbsp;<span>{{ record.userMobile }}</span>
              </div>
              <div>{{ record.userNetsignAccount }}</div>
            </div>
            <div slot="amountInfo" slot-scope="text, record">
              <div>
                <span>{{ record.depositAmount }}</span
                >/<span>{{ record.contractAmount }}</span>
              </div>
              <div>
                <span>已还{{ record.repaymentNums }}期</span>/<span>共{{ record.repaymentCycle }}期</span>
              </div>
            </div>
            <span slot="serviceFeeAmount" slot-scope="text, record">
              <span>{{
                text ? `${text}/${((record.serviceFeeAmount * 100) / record.contractAmount).toFixed(2)}` : '—'
              }}</span>
            </span>
            <span slot="repaymentDay" slot-scope="text">
              <span>{{ text | repaymentDayFilter }}</span>
            </span>
            <span slot="serviceFeePayStatus" slot-scope="text">
              <span>{{ text | serviceFeePayStatusFilter }}</span>
            </span>
            <span slot="repaymentStatus" slot-scope="text">
              <span>{{ text | repaymentStatusFilter }}</span>
            </span>
            <span slot="capitalContractStatus" slot-scope="text">
              <span>{{ text | capitalContractStatusFilter }}</span>
            </span>
          </a-table>
        </a-descriptions-item>
      </a-descriptions>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { uploadFile } from '@/api/common'
import { STable, Ellipsis } from '@/components'
import { getContractList } from '@/api/custContractManage'
// 表单字段
const fields = ['contractNo', 'serviceFeeAmount', 'pics']

const statusMap = {
  1: {
    status: 'processing',
    text: '启用'
  },
  2: {
    status: 'default',
    text: '冻结'
  }
}

const serviceFeePayStatusMap = {
  0: {
    text: '未支付'
  },
  1: {
    text: '已支付'
  }
}

const repaymentStatusMap = {
  1: {
    text: '正常'
  },
  2: {
    text: '逾期'
  },
  3: {
    text: '结清'
  }
}

const capitalContractStatusMap = {
  0: {
    text: '未打包'
  },
  1: {
    text: '已打包'
  },
  2: {
    text: '已结清'
  },
  4: {
    text: '已冻结'
  }
}

const repaymentDayMap = {
  1: {
    text: '次月今日'
  },
  2: {
    text: '次月5日'
  },
  3: {
    text: '次月15日'
  },
  4: {
    text: '次月25日'
  },
  5: {
    text: '一周后'
  },
  6: {
    text: '本月月底'
  }
}

const columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' },
    align: 'center',
    fixed: 'left',
    width: 80
  },
  {
    title: '合同编号',
    dataIndex: 'contractNo',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '签约人',
    dataIndex: 'userName',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '签约时间',
    dataIndex: 'netsignCompleteTime',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '定金/金额',
    dataIndex: 'amountInfo',
    scopedSlots: { customRender: 'amountInfo' },
    align: 'center'
  }
]

function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}

export default {
  components: {
    STable,
    Ellipsis
  },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    title: {
      type: String,
      default: ''
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    this.columns = columns
    return {
      form: this.$form.createForm(this),
      previewVisible: false,
      previewImage: '',
      queryParam: {},
      fileList: [],
      selectedRowKeys: [],
      selectedRows: [],
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getContractList(requestParameters)
          .then((res) => {
            return res.result
          })
          .catch((e) => {})
      }
    }
  },
  methods: {
    /**
     * 提交表单
     */
    _submit: function () {
      this.$emit('ok', { contractList: this.selectedRowKeys })
    },
    /**
     * 取消
     */
    _cancel: function () {
      this.$emit('cancel')
    },
    handleCancel () {
      this.previewVisible = false
    },
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },

    customRequest (options) {
      const params = new FormData()
      this.uploadLoading = true
      params.append('file', options.file)
      params.append('uploadType', 'merchant')
      uploadFile(params)
        .then((res) => {
          this.fileList.push({
            uid: this.fileList.length - 1,
            name: options.file.name,
            status: 'done',
            url: res.url
          })
          this.form.setFieldsValue({
            pics: this.fileList.map((item) => item.url).join(',')
          })
        })
        .catch((e) => {})
    },
    /**
     * 删除图片
     */
    delFile (options) {
      const curIndex = this.fileList.findIndex((item) => {
        return item.name === options.name
      })
      this.fileList.splice(curIndex, 1)
      this.form.setFieldsValue({
        pics: this.fileList.map((item) => item.url).join(',')
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    },
    serviceFeePayStatusFilter (type) {
      return serviceFeePayStatusMap[type].text
    },
    repaymentStatusFilter (type) {
      return repaymentStatusMap[type].text
    },
    capitalContractStatusFilter (type) {
      return capitalContractStatusMap[type].text
    },
    repaymentDayFilter (type) {
      return repaymentDayMap[type].text
    }
  },
  created () {
    this.$watch('visible', () => {
      this.selectedRowKeys = []
      this.selectedRows = []
      this.fileList = []
    })
    // 防止表单未注册
    fields.forEach((v) => this.form.getFieldDecorator(v))
    this.$watch('model', () => {
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  },
  mounted () {}
}
</script>
<style lang="less" scope>
.tableTitle {
  padding: 0 0 20px;
}
.contractNo {
  display: inline;
  width: 200px;
}
.handleBtns {
  padding: 0 20px;
}
</style>
